/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gpstracking.DA;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.gpstracking.BE.Area;
import com.gpstracking.BE.Punto;
import com.gpstracking.BE.Usuario;
import com.gpstracking.Utils.Geometry.Point;
import com.gpstracking.Utils.Geometry.Polygon;

/**
 *
 * @author jmj
 */
public class AreaDA {

    public static Polygon getPoly(Area area) {
        Set setPuntos = area.getPuntos();
    	Iterator it = setPuntos.iterator();
    	List<Point> tmp = new ArrayList<Point>();
    	
    	while( it.hasNext() ){
    		Punto punto = (Punto) it.next();
    		tmp.add( new Point(punto.getLatitud(), punto.getLongitud()) );
    	}
    	
        return new Polygon(tmp);
    }

    public static boolean save(Area area, List<Punto> Puntos) {
    	
    	Session hbsession = null;
        try{
        	hbsession = HUtil.getSession();
        	
        	
        	
            Transaction tx = hbsession.beginTransaction();
            tx.begin();
            
            int idArea = area.getIdArea();
            if ( idArea == 0 ){
            	hbsession.save(area);	
            }
            
        	
            
            for( Punto it : Puntos ){
                hbsession.save( it ) ;
            }
            
            if ( idArea != 0 ){
            	hbsession.update( area );
            	
            }
            
            
            
            tx.commit();
            
            return true;
        }catch(Exception ex){
            ex.printStackTrace();
            
            return false;
        }
    }

    public static Area get(int id, Usuario user) {
        Session hbsession = HUtil.getSession();
        Transaction tx = hbsession.beginTransaction();
		tx.begin();
        Query query = hbsession.createQuery("FROM Area WHERE idArea = :idArea AND usuario.idUsuario = :iduser");
        query.setParameter("idArea", id);
        query.setParameter("iduser", user.getIdUsuario());
        List<Area> res = (List<Area>) query.list();
        
        return res.isEmpty() ? null : res.get(0);
    }

	public static List<Area> getActivas(Usuario user) {
		Session hbsession = HUtil.getSession();
		Transaction tx = hbsession.beginTransaction();
		tx.begin();
        Query query = hbsession.createQuery("FROM Area WHERE usuario.idUsuario = :iduser");
        query.setParameter("iduser", user.getIdUsuario());
        List<Area> res = (List<Area>) query.list();
        
        return res;
	}
    
}
